package pl.edu.agh.iosr.gamblingzone.action;

import java.util.Date;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import static org.jboss.seam.ScopeType.SESSION;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.UserDAOBean;
import pl.edu.agh.iosr.gamblingzone.model.User;

/**
 * This is examplary code. It works, but it needs some improvements :D
 * @author maciej
 *
 */

@Stateless
@Name("authenticator")
public class MyAuthenticatorAction implements MyAuthenticator
{
   @Logger Log log;
    
   @PersistenceContext EntityManager em;

   @In Identity identity;
   
   @Out(required=false, scope = SESSION)
   private User user;
   
    public boolean authenticate()
    {
    	// Now if you want to modify some user in database
    	// you must create a UserDAOBean instance (or e.g. DisciplineDAOBean)
    	// this is extra level of abstraction
    	// every operation on persistent object must be done via DAO instance
    	UserDAOBean userDAO = new UserDAOBean();

    	// next we pass by value an entity Manager
    	// as yet, I don't know how to inject it to DAO :D
    	// so it must be done this way
    	userDAO.setEntityManager(em);
    	
    	// Below is simple authentication code, it checks whether user exist in database
    	// then checks login & password
    	
        // Authenticate user via DAO	
	if(!userDAO.authenticateUser(identity.getUsername(), identity.getPassword())) {
    		// There is no such user => fail
        	log.info("Authenticate #0", "Wrong user: "+identity.getUsername()+
        			" or password: "+identity.getPassword());
        	return false;	
        }
        else {
		log.info("Authenticate #0", identity.getUsername()+
				" successfully authorized "+identity.getPassword());
	
		// Here we are authenticated, user with given login and password exists in
		// database, now we are getting persistent object representing User
		// from database 
		// method findByLogin is implemented by me in DAO, if you need some
		// other functionality from any DAO class just tell me
		// I'll do my best :D (or make an issue radzisz loves that)
		user = userDAO.findByLogin(identity.getUsername());

		log.info("user retrievede #0", user.getLoginName()+
				" | "+user.getPassword());
	
		// From now on we've got persistent object  
		// we're getting role of the user and set it in identity
		// identity.addRole(user.getRole());
		
		// M'kay this is the end, Seam automatically commit changes to database
		// we're done :D take a break for a coffee
		return true;
        }
    }
}
